/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: yinsh
 * Date: 2025-02-21
 * Time: 19:34
 */
public class Test {
    static class TreeNode {
        int val;
        TreeNode right;
        TreeNode left;

        public TreeNode (int val) {
            this.val =  val;
        }

    }
    TreeNode root = null;
    public boolean search (int val) {
        TreeNode cur = root;
        if (root == null) return false;
        while (cur != null) {
            if (cur.val == val) {
                return true;
            }
            if (cur.val < val) {
                cur = cur.right;
            }else if (cur.val > val) {
                cur = cur.left;
            }else {
                return true;
            }
        }
        return false;
    }

    public boolean insert (int val) {
        TreeNode treeNode = new TreeNode(val);
        TreeNode cur = root;
        TreeNode parent = cur;
        if (root == null) {
            root = treeNode;
            return true;
        }
        while (cur != null) {
            if (cur.val > val) {
                parent = cur;
                cur = cur.left;
            } else if (cur.val < val) {
                parent = cur;
                cur = cur.right;
            } else {
                return false;
            }
        }
        if (parent.val > val) {
            parent.left = treeNode;
        }else if (parent.val < val) {
            parent.right = treeNode;
        }else {
            return false;
        }
        return true;
    }

    public boolean remove (int val) {
        TreeNode cur = root;
        TreeNode parent = null;
        if (root == null) {
            return false;
        }
        while (cur != null) {
            if (cur.val > val) {
                parent = cur;
                cur = cur.left;
            } else if (cur.val < val) {
                parent = cur;
                cur = cur.right;
            } else {
                removeNode(cur);
                return true;
            }
        }
        return false;
    }

    private void removeNode (TreeNode cur) {
        TreeNode targetParent = cur;
        TreeNode target = cur.left;
        while (target.right != null) {
            targetParent = target;
            target = targetParent.right;
            if (target == targetParent.left) {
                cur.val = target.val;
                targetParent.left = target.left;
            } else {
                cur.val = target.val;
                targetParent.right = target.left;
            }
        }
    }
}
